import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:kq_flutter_widgets/config/kq_global.dart';
import 'package:kq_flutter_widgets/resources/images.dart';
import 'package:kq_flutter_widgets/widgets/divider/kq_divider.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/widgets/third/pull_down_button/src/pull_down_button.dart';
import '../../resources/kq_theme_colors.dart';

import '../../theme/kq_theme_manager.dart';
import 'pull_down_menu_controller.dart';

// typedef OnItemTap<T> = void Function(T value);
typedef OverlayBack = Widget Function();

// ignore: must_be_immutable
class PullDownHeader extends StatefulWidget {
  final GlobalKey stackKey;

  /// 控制器
  PullDownMenuController controller;

  ///标题绘制器，返回标题要显示的文本内容
  final String Function(dynamic item, int menuIndex) titleRender;

  ///指定位置是否外部自己控制header数据的刷新,自定义widget必须外部控制数据更新，如果true或者未实现回调，则需外部自己刷新，如果false则内容做更新
  bool Function(int index)? isSelfControlHeaderData;

  /// 指定位置自定义,如果需要自定义返回widget，否则返回null
  Widget? Function(int index, PullDownMenuController menuController)?
      renderCustomHeaderView;

  /// 当前菜单回调，展开还是收起
  void Function(int index, bool isShow, PullDownMenuController menuController)?
      getCurrentStatus;

  /// 指定头部header每个item的宽度
  double Function(int index)? headerViewWidth;

  ///初始化数据
  List<dynamic> initChosenData;

  ///header高度，默认44
  final double height;

  ///边框线的颜色
  final Color borderColor;

  ///背景色
  final Color bgColor;

  ///样式
  final TextStyle? style;

  ///下拉展开后的样式
  final TextStyle? dropDownStyle;

  ///icon下拉颜色
  final Color? iconDropDownColor;

  ///icon大小
  final double iconSize;

  ///icon默认颜色
  final Color iconColor;

  ///是否使用overlay
  final bool isUseOverlay;

  ///是否禁止下拉
  final bool Function(int menuIndex)? disabledRender;

  ///是否展示下拉上拉按钮
  final bool Function(int menuIndex)? visibleRender;

  /// 右侧筛选宽度
  final double? rightFilterWidth;

  /// 是否支持右侧筛选
  final bool isSupportRightFilter;

  OverlayBack? menuListOverlay;

  Future<void> Function()? showMenu;

  /// 头部每个item点击的时候是否展示背景蒙版
  bool Function(int menuIndex)? ifShowMenu;

  PullDownHeader({
    Key? key,
    required this.stackKey,
    required this.controller,
    required this.titleRender,
    required this.initChosenData,
    this.isSelfControlHeaderData,
    this.renderCustomHeaderView,
    this.disabledRender,
    this.visibleRender,
    this.getCurrentStatus,
    this.headerViewWidth,
    this.height = 44,
    this.borderColor = KqThemeColors.bgF0,
    this.bgColor = Colors.white,
    this.style,
    this.dropDownStyle,
    this.iconDropDownColor,
    this.iconSize = 20,
    this.rightFilterWidth,
    this.isSupportRightFilter = false,
    this.iconColor = KqThemeColors.text26,
    this.isUseOverlay = false,
    this.menuListOverlay,
    this.showMenu,
    this.ifShowMenu,
  }) : super(key: key);

  @override
  State<PullDownHeader> createState() => _PullDownHeaderState();
}

class _PullDownHeaderState extends State<PullDownHeader> {
  bool _isShowDropDownItemWidget = false;
  final GlobalKey _keyDropDownHeader = GlobalKey();
  final TextStyle _dropDownStyle = TextStyle(
      color: KqThemeManager.getPullDownMenuConfig().selectColor ??
          KqThemeColors.bgBlue,
      fontSize: KqThemeManager.getPullDownMenuConfig().headFontSize);

  final TextStyle _normalStyle = TextStyle(
      color: KqThemeColors.text26,
      fontSize: KqThemeManager.getPullDownMenuConfig().headFontSize);

  Color? _iconDropDownColor;

  OverlayEntry? _overlayEntry;

  @override
  void initState() {
    super.initState();
    initControllerChosenData();
    widget.controller.addListener(_onController);
  }

  void initControllerChosenData() {
    Map<int, dynamic> chosenData = {};
    for (var i = 0; i < widget.initChosenData.length; i++) {
      var item = widget.controller.chosenData[i];
      if (widget.isSelfControlHeaderData != null) {
        bool isSelfControl = widget.isSelfControlHeaderData!(i);
        if (isSelfControl) {
          chosenData[i] = widget.initChosenData[i];
        } else {
          if (item != null) {
            chosenData[i] = item;
          } else {
            chosenData[i] = widget.initChosenData[i];
          }
        }
      } else {
        if (item != null) {
          chosenData[i] = item;
        } else {
          chosenData[i] = widget.initChosenData[i];
        }
      }
    }
    widget.controller.chosenData = chosenData;
  }

  _onController() {
    if (widget.controller.isRemoveMenu) {
      widget.controller.isRemoveMenu = false;
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    MediaQueryData mediaQuery = MediaQuery.of(context);
    //屏幕宽度
    var screenWidth = mediaQuery.size.width;
    return Container(
      key: _keyDropDownHeader,
      height: widget.height,
      decoration: BoxDecoration(
        border:
            Border(bottom: BorderSide(width: 0.5, color: widget.borderColor)),
      ),
      child: widget.headerViewWidth != null && !widget.isSupportRightFilter
          ? Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: _renderHeaderView(),
            )
          : Row(
              children: [
                Expanded(
                    child: GridView.count(
                  padding: const EdgeInsets.symmetric(vertical: 0),
                  crossAxisCount: widget.initChosenData.length,
                  //禁止滑动
                  physics: const NeverScrollableScrollPhysics(),
                  childAspectRatio: widget.isSupportRightFilter
                      ? ((screenWidth - (widget.rightFilterWidth ?? 50.r)) /
                              widget.initChosenData.length) /
                          widget.height
                      : (screenWidth / widget.initChosenData.length) /
                          widget.height,
                  children: _renderHeaderView(),
                )),
                // 这里添加自定义View
                if (widget.isSupportRightFilter)
                  GestureDetector(
                    onTap: () {
                      if (widget.controller.isShow) {
                        if (widget.controller.menuIndex ==
                            widget.initChosenData.length) {
                          widget.getCurrentStatus?.call(
                              widget.initChosenData.length,
                              false,
                              widget.controller);
                          widget.controller.hide();
                          closePullDownMenu(context);
                        } else {
                          widget.controller.hide(isShowHideAnimation: false);
                          widget.controller.show(widget.initChosenData.length);
                          widget.getCurrentStatus?.call(
                              widget.initChosenData.length,
                              true,
                              widget.controller);
                          widget.showMenu?.call();
                        }
                      } else {
                        widget.controller.show(widget.initChosenData.length);
                        if (widget.isUseOverlay) {
                          widget.getCurrentStatus?.call(
                              widget.initChosenData.length,
                              true,
                              widget.controller);
                          widget.controller.reload();
                          widget.showMenu?.call();
                        } else {
                          widget.getCurrentStatus?.call(
                              widget.initChosenData.length,
                              true,
                              widget.controller);
                          widget.showMenu?.call();
                        }
                      }
                      setState(() {});
                    },
                    child: Row(
                      children: [
                        const KqVerticalDivider(),
                        Container(
                          color: KqThemeColors.bgWhite,
                          width: widget.rightFilterWidth ?? 50.r,
                          height: widget.height,
                          child: Align(
                            alignment: Alignment.center,
                            child: Image.asset(
                              Images.commonIcSift20White,
                              width: 18.r,
                              height: 18.r,
                              package: KqGlobal.packageName,
                              fit: BoxFit.fill,
                            ),
                          ),
                        )
                      ],
                    ),
                  )
              ],
            ),
    );
  }

  @override
  dispose() {
    widget.controller.removeListener(_onController);
    super.dispose();
  }

  void showCustomMenu(int index) {
    int menuIndex = widget.controller.menuIndex;

    if (index == menuIndex && Get.isRegistered<PullDownMenuController>()) {
      if (widget.controller.isShow) {
        widget.getCurrentStatus?.call(index, false, widget.controller);
        widget.controller.hide();
        // _hideOverlay();
      } else {
        widget.controller.show(index);
        // _operateOverlay();
        if (widget.isUseOverlay) {
          widget.controller.reload();
          widget.getCurrentStatus?.call(index, true, widget.controller);
        } else {
          widget.getCurrentStatus?.call(index, true, widget.controller);
        }
      }
    } else if (Get.isRegistered<PullDownMenuController>()) {
      if (widget.controller.isShow) {
        widget.controller.hide(isShowHideAnimation: false);
        widget.controller.show(index);
        widget.getCurrentStatus?.call(index, true, widget.controller);
      } else {
        widget.controller.show(index);
        // _operateOverlay();
        if (widget.isUseOverlay) {
          widget.controller.reload();
          widget.getCurrentStatus?.call(index, true, widget.controller);
        } else {
          widget.getCurrentStatus?.call(index, true, widget.controller);
        }
      }
    }
    setState(() {});
  }

  // void _operateOverlay() {
  //   if (!widget.controller.isShow) {
  //     _hideOverlay();
  //   } else {
  //     _showOverlay();
  //   }
  // }

  // void _hideOverlay() {
  //   if (widget.isUseOverlay && _overlayEntry != null) {
  //     _overlayEntry!.remove();
  //     _overlayEntry = null;
  //   }
  // }

  // void _showOverlay() {
  //   if (widget.isUseOverlay) {
  //     _overlayEntry = _createOverlayEntry();
  //     Overlay.of(context).insert(_overlayEntry!);
  //   }
  // }

  // OverlayEntry _createOverlayEntry() {
  //   Widget menu = widget.menuListOverlay!();
  //   return OverlayEntry(
  //       builder: ((context) => Stack(
  //             children: [menu],
  //           )));
  // }

  _renderHeaderView() {
    List<Widget> items = <Widget>[];
    initControllerChosenData();
    for (var i = 0; i < widget.initChosenData.length; i++) {
      var showItem = widget.initChosenData[i];
      if (widget.isSelfControlHeaderData != null) {
        bool isSelfControl = widget.isSelfControlHeaderData!(i);
        if (isSelfControl) {
          showItem = widget.initChosenData[i];
        } else {
          var item = widget.controller.chosenData[i];
          if (item != null) {
            showItem = item;
          } else {
            showItem = widget.initChosenData[i];
          }
        }
      } else {
        if (Get.isRegistered<PullDownMenuController>()) {
          var item = widget.controller.chosenData[i];
          if (item != null) {
            showItem = item;
          } else {
            showItem = widget.initChosenData[i];
          }
        } else {
          showItem = widget.initChosenData[i];
        }
      }
      if (widget.renderCustomHeaderView != null) {
        Widget? view = widget.renderCustomHeaderView!(i, widget.controller);
        if (view != null) {
          items.add(Expanded(
              child: SizedBox(
            height: widget.height,
            child: view,
          )));
        } else {
          items.add(_menu(i, showItem));
        }
      } else {
        items.add(_menu(i, showItem));
      }
    }
    return items.toList();
  }

  _menu(int index, dynamic item) {
    int menuIndex = widget.controller.menuIndex;
    _isShowDropDownItemWidget = index == menuIndex && widget.controller.isShow;
    _iconDropDownColor = widget.iconDropDownColor ??
        KqThemeManager.getPullDownMenuConfig().selectColor;

    String title = widget.titleRender(item, index);

    bool disabled = false;
    if (widget.disabledRender != null) {
      disabled = widget.disabledRender!(index);
    }
    return GestureDetector(
      onTap: () {
        if (disabled) {
          return;
        }
        // 通过await还是会导致被退出，只能通过延迟处理
        action(index, menuIndex);
      },
      child: widget.headerViewWidth != null
          ? Container(
              width: widget.headerViewWidth!(index),
              color: widget.bgColor,
              child: renderHeaderItem(index, title),
            )
          : Container(
              color: widget.bgColor,
              child: renderHeaderItem(index, title),
            ),
    );
  }

  action(int index, int menuIndex) {
    //使用Overlay
    // if (widget.isUseOverlay) {
    //   final RenderBox dropDownItemRenderBox =
    //       _keyDropDownHeader.currentContext!.findRenderObject() as RenderBox;
    //   var position = dropDownItemRenderBox.localToGlobal(Offset.zero);
    //   var size = dropDownItemRenderBox.size;
    //   if (Get.isRegistered<PullDownMenuController>()) {
    //     widget.controller.dropDownMenuTop = size.height + position.dy;
    //   }
    // } else {
    //   final RenderBox? overlay =
    //       widget.stackKey.currentContext!.findRenderObject() as RenderBox?;
    //
    //   final RenderBox dropDownItemRenderBox =
    //       _keyDropDownHeader.currentContext!.findRenderObject() as RenderBox;
    //   var position =
    //       dropDownItemRenderBox.localToGlobal(Offset.zero, ancestor: overlay);
    //   var size = dropDownItemRenderBox.size;
    //   widget.controller.dropDownMenuTop = size.height + position.dy;
    // }

    if (index == menuIndex) {
      if (widget.controller.isShow) {
        widget.getCurrentStatus?.call(index, false, widget.controller);
        widget.controller.hide();

        closePullDownMenu(context);
        // _hideOverlay();
      } else {
        // widget.controller.show(index);
        show(index);
        // _operateOverlay();
        if (widget.isUseOverlay) {
          widget.controller.reload();
          widget.getCurrentStatus?.call(index, true, widget.controller);
          showMenu(index);
        } else {
          widget.getCurrentStatus?.call(index, true, widget.controller);
          showMenu(index);
        }
      }
    } else if (Get.isRegistered<PullDownMenuController>()) {
      if (widget.controller.isShow) {
        widget.controller.hide(isShowHideAnimation: false);
        // widget.controller.show(index);
        show(index);
        widget.getCurrentStatus?.call(index, true, widget.controller);
        showMenu(index);
      } else {
        // widget.controller.show(index);
        show(index);
        // _operateOverlay();
        if (widget.isUseOverlay) {
          widget.getCurrentStatus?.call(index, true, widget.controller);
          widget.controller.reload();
          showMenu(index);
        } else {
          widget.getCurrentStatus?.call(index, true, widget.controller);
          showMenu(index);
        }
      }
    }
    setState(() {});
  }

  void show(int index) {
    if (widget.ifShowMenu != null) {
      bool ifShow = widget.ifShowMenu!.call(index);
      if (ifShow) {
        widget.controller.show(index);
      }
    } else {
      widget.controller.show(index);
    }
  }

  void showMenu(int index) {
    if (widget.ifShowMenu != null) {
      bool ifShow = widget.ifShowMenu!.call(index);
      if (ifShow) {
        widget.showMenu?.call();
      }
    } else {
      widget.showMenu?.call();
    }
  }

  Widget renderHeaderItem(int index, String title) {
    bool disabled = false;
    if (widget.disabledRender != null) {
      disabled = widget.disabledRender!(index);
    }
    bool visible = true;
    if (widget.visibleRender != null) {
      visible = widget.visibleRender!(index);
    }
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Expanded(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Flexible(
                child: Text(
                  title.replaceAll('', '\u200b'),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: disabled
                      ? TextStyle(
                          fontSize: _normalStyle.fontSize,
                          color: KqThemeColors.textBF)
                      : _isShowDropDownItemWidget
                          ? widget.dropDownStyle ?? _dropDownStyle
                          : widget.style ?? _normalStyle,
                ),
              ),
              if (visible)
                Icon(
                  !_isShowDropDownItemWidget
                      ? Icons.keyboard_arrow_down
                      : Icons.keyboard_arrow_up,
                  color: disabled
                      ? KqThemeColors.textBF
                      : _isShowDropDownItemWidget
                          ? _iconDropDownColor ??
                              KqThemeManager.getCommonConfig().mainColor ??
                              KqThemeColors.bgBlue
                          : widget.iconColor,
                  size: widget.iconSize,
                  fill: 1,
                ),
            ],
          ),
        ),
        index == widget.initChosenData.length - 1
            ? Container()
            : Container(
                height: widget.height,
                decoration: BoxDecoration(
                  border: Border(
                    right: BorderSide(color: widget.borderColor, width: 1),
                  ),
                ),
              ),
      ],
    );
  }
}
